#include <windows.h>
#include <tchar.h>
#include <stdlib.h>
#include "dllmain.h"
#include "ini.h"
#include "log.h"

//char * regpath="Software\\FM2i\\tracelog";
//HKEY   hRootKey=NULL;
_TCHAR iniFileName[1024];

/********>>> SPECIAL FUNCTIONS FOR OPALE.INI**********/
BOOL ini_getShowTraceLog(){
	_TCHAR buf[10];
	GetPrivateProfileString(_T("options"), _T("debug"), _T(""), buf, 10, iniFileName);
	if(!_tcsicmp(buf,_T("Y")))return true;
	return false;
}
long ini_getBasicMaskSet(){
	_TCHAR buf[20]=_T("0");
	GetPrivateProfileString(_T("options"), _T("mask.file"), _T("0"), buf, 20, iniFileName);
	return _ttol(buf);
}

/********<<< SPECIAL FUNCTIONS FOR OPALE.INI**********/





//initialize work with settings
BOOL ini_init(){
	if (!GetModuleFileName(getInstance(),iniFileName, NUMTCHARS(iniFileName)))return log_error(_T("ini_init.GetModuleFileName"));
	_tcscpy(iniFileName,iniFileName);
	//tracelog.dll
	_tcscpy(iniFileName+_tcslen(iniFileName)-3,_T("ini"));
	log(_T("DBG: ini_init.iniFileName = \"%s\".\n"),iniFileName);
	return true;
}

//finalize work with settings
BOOL ini_finit(){
//	if(RegCloseKey(hRootKey)==ERROR_SUCCESS)return 1;
	return true;
}

//returns reference to value
//buffer should be large enough to store the value otherwise it will be trancated
//default can not be NULL!
_TCHAR * ini_getstr(_TCHAR * section,_TCHAR*key,_TCHAR*def,_TCHAR*val,int vallen){
	GetPrivateProfileString(section, key, def, val, vallen, iniFileName);
	return val;
}
BOOL   ini_setstr(_TCHAR * section,_TCHAR*key,_TCHAR*val){
	if(WritePrivateProfileString(section, key, val, iniFileName) )return 1;
	return log_error(_T("ini_setstr"));
}

int    ini_getint(_TCHAR * section,_TCHAR*key,int def){
	_TCHAR cbuf[20];
	_TCHAR cdef[20];
	_ltot( def,cdef,10 );
	return _ttoi( ini_getstr( section, key, cdef, cbuf, 20 ) );
}

BOOL   ini_setint(_TCHAR * section,_TCHAR*key,int val){
	_TCHAR cbuf[20];
	_ltot(val, cbuf, 10);
	return ini_setstr(section, key,cbuf);
}


BOOL ini_savewinpos(_TCHAR*section,HWND hwnd){
	RECT  * rc;
	WINDOWPLACEMENT wp;
	GetWindowPlacement(hwnd,&wp);
	rc = &wp.rcNormalPosition;
	ini_setint(section,_T("x"),rc->left);
	ini_setint(section,_T("y"),rc->top);
	ini_setint(section,_T("w"),rc->right - rc->left);
	ini_setint(section,_T("h"),rc->bottom - rc->top);
	return 1;
}

BOOL ini_loadwinpos(_TCHAR*section,HWND hwnd){
	RECT  * rc;
	WINDOWPLACEMENT wp;
	//get old values
	GetWindowPlacement(hwnd,&wp);
	rc = &wp.rcNormalPosition;
	//apply new
	SetWindowPos(hwnd,NULL,
		ini_getint(section,_T("x"),rc->left),	// horizontal position
		ini_getint(section,_T("y"),rc->top),	// vertical position
		ini_getint(section,_T("w"),rc->right - rc->left),	// width
		ini_getint(section,_T("h"),rc->bottom - rc->top),	// height
		SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOZORDER);
	return 1;
}

